package com.deer.wms.ASN.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deer.wms.ASN.manage.dao.AcceptLogMapper;
import com.deer.wms.ASN.manage.model.AcceptLog;
import com.deer.wms.ASN.manage.model.in.AcceptLogCriteria;
import com.deer.wms.ASN.manage.service.AcceptLogService;
import com.deer.wms.base.system.model.http.HttpClientss;
import com.deer.wms.inventory.dao.InventoryMapper;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.InventoryVo;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.system.manage.dao.WareInfoMapper;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.ware.task.dao.SoLogMapper;
import com.deer.wms.ware.task.model.SoLog;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service
@Transactional
public class AcceptLogServiceImpl extends ServiceImpl<AcceptLogMapper, AcceptLog> implements AcceptLogService {

    @Resource
    private AcceptLogMapper acceptLogMapper;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private WareInfoMapper wareInfoMapper;

    @Autowired
    private SoLogMapper soLogMapper;

    @Override
    public Date getMaxLogDate() {
        return acceptLogMapper.getLogMaxDate();
    }

    @Override
    public PageInfo findList(AcceptLogCriteria acceptLogCriteria) {
        PageHelper.startPage(acceptLogCriteria.getPageNum(), acceptLogCriteria.getPageSize());
        List<AcceptLog> list = acceptLogMapper.findList(acceptLogCriteria);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 盘存单查询
     * @param hashMap 条件
     */
    @Override
    public Object selectInventory(Map<String, Object> hashMap) {
        //获取盘存单数据
        List<InventoryVo> list = findList(hashMap);
        if (list.size() == 0){
            return list;
        }
        list.stream().forEach(t->{
            LambdaQueryWrapper<Inventory> queryWrapper = new LambdaQueryWrapper<>();
            //批号编码 ； 料品编码 ； 存储地点编码；盘点单号；
            queryWrapper.eq(Inventory::getLotCode,t.getLotCode());//批号编码
            queryWrapper.eq(Inventory::getItemCode,t.getItemCode());//料品编码
            List<Inventory> inventories = inventoryMapper.selectList(queryWrapper);
            if (inventories.size() > 0){
                Inventory inventory = inventories.get(0);
                //修改 accQty 账存数量   checkQty	实盘数量  diffQty 差异数量
                if (inventory != null){
                    inventory.setLotCode(t.getLotCode());
                    inventory.setDiffQty(inventory.getDiffQty() == null?0d:inventory.getDiffQty());
                    inventory.setDiffQty(inventory.getDiffQty()+t.getDiffQty() >= 0?inventory.getDiffQty()+t.getDiffQty():inventory.getDiffQty());
                    inventoryMapper.updateById(inventory);
                }
                if (t.getDiffQty() >= 0){//添加盘盈记录
                    AcceptLog acceptLog = new AcceptLog();
                    acceptLog.setDocumentsId(t.getId());//单据ID
                    acceptLog.setErpNo(t.getErpNo());//盘点单
                    acceptLog.setErpLine(t.getErpLine());//盘点单行
                    acceptLog.setErpLineNo(t.getErpLineNo());// 盘点单行号
                    acceptLog.setMakeDate(t.getMakeDate());//制单时间
                    acceptLog.setMakeEmpNo(t.getMakeEmpNo());//制单人编码
                    acceptLog.setInventEmpNo(t.getInventEmpNo());//盘点执行人编码
                    acceptLog.setInventTime(t.getInventTime());//盘点日期
                    acceptLog.setWareCode(t.getWareCode());//存储地点编码
                    acceptLog.setAccQty(t.getAccQty());//账存数量
                    acceptLog.setCheckQty(t.getCheckQty());//实盘数量
                    acceptLog.setDiffQty(t.getDiffQty());//差异数量
                    acceptLog.setLotCode(t.getLotCode());//批号编码
                    acceptLog.setStatus(t.getStatus());//盘点单状态（1 开立,2 盘点，3 核准中，4 已核准）
                    acceptLog.setOrg(t.getOrg());//组织ID
                    acceptLogMapper.insert(acceptLog);
                }else{//添加盘亏记录
                    SoLog soLog = new SoLog();
                    soLog.setDocumentsId(t.getId());//单据ID
                    soLog.setErpNo(t.getErpNo());//盘点单
                    soLog.setErpLine(t.getErpLine());//盘点单行
                    soLog.setErpLineNo(t.getErpLineNo());// 盘点单行号
                    soLog.setMakeDate(t.getMakeDate());//制单时间
                    soLog.setMakeEmpNo(t.getMakeEmpNo());//制单人编码
                    soLog.setInventEmpNo(t.getInventEmpNo());//盘点执行人编码
                    soLog.setInventTime(t.getInventTime());//盘点日期
                    soLog.setWareCode(t.getWareCode());//存储地点编码
                    soLog.setAccQty(t.getAccQty());//账存数量
                    soLog.setCheckQty(t.getCheckQty());//实盘数量
                    soLog.setDiffQty(t.getDiffQty());//差异数量
                    soLog.setLotCode(t.getLotCode());//批号编码
                    soLog.setStatus(t.getStatus());//盘点单状态（1 开立,2 盘点，3 核准中，4 已核准）
                    soLog.setOrg(t.getOrg());//组织ID
                    soLogMapper.insert(soLog);
                }
            }
        });
        return list;
    }

    /**
     * 盘存单数据
     * @param hashMap
     * @return
     */
    public List<InventoryVo> findList(Map<String, Object> hashMap){
        List<InventoryVo> billList = new ArrayList<>();
        //查询盘存单查询数据
        Map<String, Object> returnMap = HttpClientss.getDateFromERP2("http://61.160.125.186:5555/zp/api/ZpViewInv/Query", HttpMethod.POST, hashMap);
        if (returnMap.get("code")!= null && "200".equals(returnMap.get("code").toString())){
            if (returnMap.get("result")!= null){
                JSONArray jsonArray = JSONArray.parseArray(String.valueOf(returnMap.get("result")));
                billList = JSONObject.parseArray(jsonArray.toJSONString(), InventoryVo.class);
            }else {
                System.out.println("查询ERP单据信息为空！");
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息为空！");
            }
        }else {
            System.out.println("查询ERP单据信息失败！");
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"查询ERP单据信息失败！");
        }
        return billList;
    }


    /**
     * 调用第三方接口
     * @param pathUrl 地址
     * @param data    参数
     * @return
     */
    public static Map<String,Object> doPostOrGet(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        Map<String, Object> map = new HashMap<>();
        try {
            URL url = new URL(pathUrl);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("POST");
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            conn.setDoOutput(true);
            conn.setDoInput(true);

            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            map = JSON.parseObject(result);
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
